package com.example.clxy.service.impl;

import com.example.clxy.dao.RoleMapper;
import com.example.clxy.dao.UserMapper;
import com.example.clxy.dao.WlclassMapper;
import com.example.clxy.entity.Unbind;
import com.example.clxy.entity.User;
import com.example.clxy.entity.Wlclass;
import com.example.clxy.entity.dto.LoginUserDto;
import com.example.clxy.result.PageResult;
import com.example.clxy.result.WebRestResult;
import com.example.clxy.result.business.PageResult.UserPageResult;
import com.example.clxy.result.business.UserAccountResult;
import com.example.clxy.result.business.UserResult;
import com.example.clxy.service.UserService;
import com.example.clxy.util.*;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;
import java.util.List;


/**
 * @Author liuhaoqi
 * @Date 2020/8/3 20:42
 * @Version 1.0
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    WlclassMapper wlclassMapper;

    /**
     * web端登录
     *
     * @param account
     * @param password
     * @param usertype
     * @return
     */
    @Override
    public UserResult loginWeb(String account, String password, String usertype) {
        UserResult result = new UserResult();
        String roleid = usertype;
        User user = userMapper.loginWeb(account, MD5Util.getMD5Info(password), roleid);
        if (user != null && roleMapper.getRoleNameByRoleid(user.getRoleid()).contains("管理员")) {
            String rolename = roleMapper.getRoleNameByRoleid(user.getRoleid());
            String token = JwtUtils.generateToken(user.getUserid());
            user.setPassword("");
            result.setUser(user);
            result.setToken(token);
            result.setRolename(rolename);
            result.setResult(WebRestResult.SUCCESS);
            result.setMessage("管理员登录成功");
        } else if (user != null && roleMapper.getRoleNameByRoleid(user.getRoleid()).contains("老师")) {
            String rolename = roleMapper.getRoleNameByRoleid(user.getRoleid());
            String token = JwtUtils.generateToken(user.getUserid());
            user.setPassword("");
            result.setUser(user);
            result.setToken(token);
            result.setRolename(rolename);
            result.setResult(WebRestResult.SUCCESS);
            result.setMessage("老师登录成功");
        } else if (user != null && roleMapper.getRoleNameByRoleid(user.getRoleid()).contains("学生")) {
            String rolename = roleMapper.getRoleNameByRoleid(user.getRoleid());
            String token = JwtUtils.generateToken(user.getUserid());
            user.setPassword("");
            result.setUser(user);
            result.setToken(token);
            result.setRolename(rolename);
            result.setResult(WebRestResult.SUCCESS);
            result.setMessage("学生登录成功");
        } else {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("用户名或密码错误");
        }
        return result;
    }


    @Override
    public PageResult<UserPageResult> getUserList(String roleid, String teacherid, String teachername, String grade, String classid, String studentname, String studentid, int page, int pagesize) {
        PageResult<UserPageResult> res = new PageResult<>();
        int begin = (page - 1) * pagesize;
        int end = pagesize;

        List<UserPageResult> userList = userMapper.getUserList(roleid, teacherid, teachername, grade, classid, studentname, studentid, begin, end, pagesize);
        if (userList.size() > 0) {
            res.setTotal(userList.get(0).getCnt());
            res.setPageCount(userList.get(0).getPage());
            res.setRows(userList);
            res.setResult(WebRestResult.SUCCESS);
            res.setMessage("查询用户信息成功");
        }

        return res;
    }


    @Override
    public WebRestResult updateUser(User user) {
        user.setUpdatedTime(new Date());
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(MD5Util.getMD5Info(user.getPassword()));
        }
        if ("3".equals(user.getRoleid())) {
            String studentposition = user.getStudentposition();
            Wlclass wlclass = wlclassMapper.selectByPrimaryKey(user.getStudentclassid());
            if (wlclass.getMonitorid().equals(user.getUserid())) {
                if (!"1".equals(studentposition)) {
                    wlclass.setMonitorid("");
                }
            } else if (wlclass.getStudyleaderid().equals(user.getUserid())) {
                if (!"2".equals(studentposition)) {
                    wlclass.setStudyleaderid("");
                }
            } else if (wlclass.getCoursepresidentid().equals(user.getUserid())) {
                if (!"3".equals(studentposition)) {
                    wlclass.setCoursepresidentid("");
                }
            }

            if ("1".equals(studentposition)) {
                //班长
                wlclass.setMonitorid(user.getUserid());
            } else if ("2".equals(studentposition)) {
                //学委
                wlclass.setStudyleaderid(user.getUserid());
            }else if ("3".equals(studentposition)) {
                wlclass.setCoursepresidentid(user.getUserid());
            }
            wlclassMapper.updateByPrimaryKeySelective(wlclass) ;

        }
        if (userMapper.updateByPrimaryKeySelective(user) == 1) {
            return RespUtil.successResp("更新成功");
        }
        return RespUtil.failResp("更新失败");
    }

    @Override
    public WebRestResult deleteUserByUseridList(String[] useridList) {
        User user = new User();
        user.setFlag("1");
        for (int i = 0; i < useridList.length; i++) {
            user.setUserid(useridList[i]);
            if (userMapper.updateByPrimaryKeySelective(user) != 1) {
                return RespUtil.failResp("删除到第" + (i + 1) + "个用户时出错,用户未找到");
            }
        }
        return RespUtil.successResp("删除成功");
    }


    @Override
    public WebRestResult addUser(User user) {
        Wlclass wlclass = null;
        if (user.getAccount() == null || user.getAccount().isEmpty()) {
            return RespUtil.failResp("用户账号不能为空!");
        } else if (user.getUsername() == null || user.getUsername().isEmpty()) {
            return RespUtil.failResp("用户姓名不能为空!");
        } else if (user.getRoleid() == null || user.getRoleid().isEmpty()) {
            return RespUtil.failResp("用户角色id不能为空!");
        } else if (user.getRoleid().equals("3")) {
            if (user.getStudentclassid() == null || user.getStudentclassid().isEmpty()) {
                return RespUtil.failResp("学生班级id不能为空!");
            } else {
               wlclass= wlclassMapper.selectByPrimaryKey(user.getStudentclassid());
               user.setStudentgrade(wlclass.getGrade());
            }
        }
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(MD5Util.getMD5Info(user.getPassword()));
        } else {
//            设置默认密码
            String defaultPassword = user.getAccount();
            if (defaultPassword.length() > 6) {
                defaultPassword = defaultPassword.substring(defaultPassword.length() - 6);
            }
            user.setPassword(MD5Util.getMD5Info(defaultPassword));
        }
        user.setUserid(UUIDUtil.randomUUID());
        user.setFlag("0");
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());

        String studentposition = user.getStudentposition();
        if ("3".equals(user.getRoleid())){
            if ("1".equals(studentposition)) {
                //班长
                wlclass.setMonitorid(user.getUserid());
            } else if ("2".equals(studentposition)) {
                //学委
                wlclass.setStudyleaderid(user.getUserid());
            }else if ("3".equals(studentposition)) {
                wlclass.setCoursepresidentid(user.getUserid());
            }
            wlclassMapper.updateByPrimaryKeySelective(wlclass) ;
        }
        if (userMapper.insert(user) == 1) {
            return RespUtil.successResp("成功新增用户信息!");
        }
        return RespUtil.failResp("新增用户失败!");
    }

    /**
     * 重置密码
     *
     * @param account
     * @return
     */
    @Override
    public WebRestResult resetPassword(String account) {
        WebRestResult result = new WebRestResult();
        String password = null;
        if (account.length() > 6) {
            password = "123456";
        } else {
            password = "123456";
        }
        password = MD5Util.getMD5Info(password);
        if (userMapper.resetPassword(account, password) == 1) {
            result.setResult(WebRestResult.SUCCESS);
            result.setMessage("重置密码成功！");
        } else {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("重置密码失败！");
        }
        return result;
    }

    @Override
    public WebRestResult updatePassword(String account, String password, String newpassword) {
        WebRestResult result = new WebRestResult();
        User user = userMapper.getUserByAccount(account);
        password = MD5Util.getMD5Info(password);
        if (user != null && password.equals(user.getPassword())) {
            if (userMapper.resetPassword(account, MD5Util.getMD5Info(newpassword)) == 1) {
                result.setResult(WebRestResult.SUCCESS);
                result.setMessage("修改密码成功！");
            } else {
                result.setResult(WebRestResult.FAILURE);
                result.setMessage("修改密码失败！");
            }
        } else {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("账号不存在或者原始密码错误！");
        }
        return result;
    }

    @Override
    public UserResult loginUser(String code) {
        UserResult result = new UserResult();
        String response = HttpUtils.code2Session(code);
        JSONObject jsonObject = new JSONObject(response);
        if (jsonObject.has("openid")) {
            //根据code解析出了openid
            String openid = jsonObject.getString("openid");
            User user = userMapper.getUserByOpenid(openid);
            if (user == null) {
                result.setResult(WebRestResult.FAILURE);
                result.setMessage("该微信登录用户未绑定学号/工号！请跳转到绑定页面");
            } else {
                String rolename = roleMapper.getRoleNameByRoleid(user.getRoleid());
                String token = JwtUtils.generateToken(user.getUserid());
                user.setPassword("");
                result.setUser(user);
                result.setRolename(rolename);
                result.setToken(token);
                result.setMessage("该微信登录用户已经绑定学号/工号！请跳转到相关页面");
            }
        } else {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("根据code调用微信接口获取openid等信息失败！" + jsonObject.getString("errmsg"));
        }
        return result;
    }

    @Override
    public UserAccountResult getUserInfoByAccount(String account) {
        UserAccountResult result = new UserAccountResult();
        UserAccountResult userAccountResult = userMapper.getUserInfoByAccount(account);
        if (userAccountResult == null) {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("该学号/工号在系统中未录入！");
        } else {
            BeanUtils.copyProperties(userAccountResult, result);
            result.setResult(WebRestResult.SUCCESS);
            result.setMessage("该学号/工号对应的用户信息从系统中查询成功！");
        }
        return result;
    }

    @Override
    public UserResult wxBindUser(LoginUserDto loginUserDto) {
        UserResult result = new UserResult();
        String code = loginUserDto.getCode();
        String account = loginUserDto.getAccount();
        String username = loginUserDto.getUsername();
        String nickname = loginUserDto.getNickname();
        String response = HttpUtils.code2Session(code);
        JSONObject jsonObject = new JSONObject(response);
        if (jsonObject.has("openid")) {
            User userByAccount = userMapper.getUserByAccount(account);
            if (userByAccount == null) {
                result.setResult(WebRestResult.FAILURE);
                result.setMessage("该学号在系统中还没有对应的用户信息！请联系管理员添加该学号、用户信息");
                return result;
            }
            if (!userByAccount.getUsername().equals(loginUserDto.getUsername())) {
                result.setResult(WebRestResult.FAILURE);
                result.setMessage("绑定的学号与姓名不一致,不允许绑定！");
                return result;
            }
            if (!loginUserDto.getRoleid().equals(userByAccount.getRoleid())) {
                //学生为 3 老师为2
                result.setResult(WebRestResult.FAILURE);
                result.setMessage("绑定学号/工号的页面不在此页面！请跳转到另外一个页面");
                return result;
            }
            if (userByAccount.getOpenid() != null && !"".equals(userByAccount.getOpenid())) {
                result.setResult(WebRestResult.FAILURE);
                result.setMessage("该学号/工号已经绑定了相应的微信用户，如果绑定错误 请去申请解绑！");
                return result;
            }
            String openid = jsonObject.getString("openid");
            if (userMapper.getUserByOpenid(openid) != null) {
                result.setResult(WebRestResult.FAILURE);
                result.setMessage("该微信用户只能绑定一个学号/工号");
                return result;
            }
            userByAccount.setWxname(nickname);
            userByAccount.setOpenid(openid);
            if (!userByAccount.getAccount().equals(account)) {
                result.setResult(WebRestResult.FAILURE);
                result.setMessage("学号/工号与输入的姓名不匹配，不允许绑定！");
                return result;
            }
            if (userMapper.updateByPrimaryKeySelective(userByAccount) == 1) {
                userMapper.insertSessionKey(openid, jsonObject.getString("session_key"), null);
                String rolename = roleMapper.getRoleNameByRoleid(userByAccount.getRoleid());
                String token = JwtUtils.generateToken(userByAccount.getUserid());
                userByAccount.setPassword("");
                result.setUser(userByAccount);
                result.setRolename(rolename);
                result.setToken(token);
                result.setResult(WebRestResult.SUCCESS);
                result.setMessage("微信用户绑定学号/工号成功！");
                return result;
            }
        } else {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage(jsonObject.getString("errmsg"));
            return result;
        }
        return result;
    }

    @Override
    public PageResult<UserPageResult> getWxBindList(int page, int pagesize, String roleid, String username, String account) {
        PageResult<UserPageResult> result = new PageResult<>();
        int begin = (page - 1) * pagesize;
        int end = pagesize;
        List<UserPageResult> list = null;
        if ("2".equals(roleid)) {
            list = userMapper.getWxBindList(begin,end,pagesize,roleid,username,account);
        } else if ("3".equals(roleid)) {
            list = userMapper.getWxBindList(begin,end,pagesize,roleid,username,account);
        } else {
            list = userMapper.getWxBindList(begin,end,pagesize,null,username,account);
        }
        if (list.size() > 0) {
            result.setRows(list);
            result.setTotal(list.get(0).getCnt());
            result.setPageCount(list.get(0).getPage());
            result.setMessage("获取已绑定微信号的用户成功");
            result.setResult(WebRestResult.SUCCESS);
        } else {
            result.setMessage("没有已绑定微信号的用户");
            result.setResult(WebRestResult.FAILURE);
        }
        return result;
    }

}
